import request from 'umi-request';

export default {
  namespace: 'employee',

  state: {
    list: [
      {
        key: '1',
        firstName: 'John',
        lastName: 'Brown',
        age: 32,
        address: 'New York No. 1 Lake Park',
        tags: ['nice', 'developer'],
      },
      {
        key: '2',
        firstName: 'Jim',
        lastName: 'Green',
        age: 42,
        address: 'London No. 1 Lake Park',
        tags: ['loser'],
      },
      {
        key: '3',
        firstName: 'Joe',
        lastName: 'Black',
        age: 32,
        address: 'Sidney No. 1 Lake Park',
        tags: ['cool', 'teacher'],
      },
    ],
  },

  reducers: {
    update(state, { payload }) {
      //const { employees } = payload;
      //return employees;
      const { user: newUser } = payload;

      return {
        list: state.list.map((user) =>
          user.key === newUser.key ? newUser : user,
        ),
      };
    },
    add(state, { payload }) {
      debugger;
      const { user } = payload;
      user.key =
        'UID' + String(Math.floor(Math.random() * 1000000)).padStart(6, '0');
      return {
        list: state.list.concat([user]),
      };
    },

    deleteEmployee(state, { payload }) {
      const { id: targetId } = payload;
      const a = { list: [] };
      a.list = state.list.filter((e) => e.key !== targetId);
      return a;
    },
  },

  effects: {
    *getAll(_, { call, put }) {
      const response = yield call(request.get, '/api/employees');

      yield put({
        type: 'update',
        payload: {
          employees: response,
        },
      });
    },
  },
};
